package us.mooresr.webtroopmanager.client.activity;

import us.mooresr.webtroopmanager.client.ClientFactory;
import us.mooresr.webtroopmanager.client.SecurityManager;
import us.mooresr.webtroopmanager.client.TroopManagerService;
import us.mooresr.webtroopmanager.client.TroopManagerServiceAsync;
import us.mooresr.webtroopmanager.client.place.AdminPlace;
import us.mooresr.webtroopmanager.client.place.DashboardPlace;
import us.mooresr.webtroopmanager.client.ui.LoginView;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class LoginActivity extends MyActivity implements LoginView.Presenter {

	
	public LoginActivity(ClientFactory clientFactory) {
		super(clientFactory);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		
		//  Uncomment this block to fix login issues 
		// AdminActivity adminActivity = new AdminActivity(clientFactory);
		// adminActivity.doInitializeUsers();
		
		
		
		LoginView loginView = clientFactory.getLoginView();
		loginView.setPresenter(this);
		loginView.clear();
		panel.setWidget(loginView.asWidget());
		
		
		String page = Window.Location.getParameter("page");
		if ((page != null) && (page.equals("backdoor"))) {
			goTo(new AdminPlace());
		}
		
	}

	@Override
	public void doLogin(String user, String password) {
		TroopManagerServiceAsync troopManagerService = (TroopManagerServiceAsync) GWT.create(TroopManagerService.class);
		
		AsyncCallback<Long> callback = new AsyncCallback<Long>() {

			@Override
			public void onFailure(Throwable caught) {
				SecurityManager securityManager = clientFactory.getSecurityManager();
				
				Window.alert("Login failed due to internal error");		
				securityManager.setUserId(null);
			}

			@Override
			public void onSuccess(Long result) {
				SecurityManager securityManager = clientFactory.getSecurityManager();
				securityManager.setUserId(result);
				
				if (result != null) {
					goTo(new DashboardPlace());
				} else {
					Window.alert("Login failed");
				}
				
			}
		};
		
		troopManagerService.doLogin(user, password, callback);
	}



}
